<?php
/**
 * Predis.php
 * 文件描述
 * Created on 2018/4/7 22:18
 * Create by xuanqiang
 */
namespace app\common\lib\redis;

use think\Exception;

class Predis
{
    public $redis = "";

    /**
     * 定义单列模式的变量
     */
    private static $_instance = null;

    public static function getInstance(){
        if(empty(self::$_instance)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct()
    {
        $this->redis = new \Redis();
        $result = $this->redis->connect(config('redis.host'),config('redis.port'),config('redis.out_time'));
        if($result === false){
            throw new \Exception('redis connect error');
        }
    }

    /**
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($key, $value, $time=0) {
        if(!$key) {
            return '';
        }
        if(is_array($value)){
            $value = json_encode($value);
        }
        if(!$time) {
            return $this->redis->set($key, $value);
        }
        return $this->redis->setex($key, $time, $value);
    }

    /**
     * @param $key
     * @return bool|string
     */
    public function get($key) {
        if(!$key) {
            return '';
        }
        return $this->redis->get($key);
    }
}